﻿using System;
using System.Windows.Input;

namespace Riba.MVVMSL
{
	///<summary>
	///<para>A command that can be defined from XAML or Code Behind and executed on the ViewModel</para>
	///<para>RelayCommand does not use RoutedEvents, instead it just executes a delegate</para>
	///</summary>
	///<remarks>For more informations on the Command pattern see http://en.wikipedia.org/wiki/Command_pattern and further literature.</remarks>
	public class RelayCommand : ICommand
	{
		private readonly Action<object> _executeHandler;

		///<summary>
		///<para>Initializes a new instance of the <see cref="RelayCommand"/> class</para>
		///</summary>
		///<param name="executeHandler">Delegate which executes a Method with object data.</param>
		public RelayCommand(Action<object> executeHandler)
		{
			_executeHandler = executeHandler;
		}

		///<summary>
		///<para>Enables the Command for execution.</para>
		///</summary>
		///<value>false</value>
		public bool IsEnabled
		{
			get { return _isEnabled; }
			set
			{
				if (value == _isEnabled)
					return;

				_isEnabled = value;

				if (CanExecuteChanged != null)
					CanExecuteChanged(this, EventArgs.Empty);
			}
		}
		private bool _isEnabled;

		#region ICommand

		///<summary>
		///<para>Returns wether a command can be executed or not.</para>
		///</summary>
		///<param name="parameter">A CommandParameter object that can be passed for further usage in overrides of the methods.</param>
		///<returns>true if the Command can be executed, else false.</returns>
		public bool CanExecute(object parameter)
		{
			return IsEnabled;
		}

		///<summary>
		///<para>public event EventHandler.</para>
		///</summary>
		public event EventHandler CanExecuteChanged;

		///<summary>
		///<para>Executes the Command.</para>
		///</summary>
		///<param name="parameter">A CommandParameter object that will be passed to the Eventhandler for further usage.</param>
		public void Execute(object parameter)
		{
			_executeHandler(parameter);
		}

		#endregion ICommand
	}
}
